<template>
  <div>
    <div v-if="!$common.isEmpty(article)">
      <!-- 封面 -->
      <div class="article-head my-animation-slide-top">
        <!-- 背景图片 -->
        <el-image
          class="article-image my-el-image"
          v-once
          lazy
          :src="article.articleCover"
          fit="cover"
        >
          <div slot="error" class="image-slot">
            <div class="article-image"></div>
          </div>
        </el-image>
        <!-- 文章信息 -->
        <div class="article-info-container">
          <div class="article-title">{{ article.articleTitle }}</div>
          <div class="article-info">
            <svg
              viewBox="0 0 1024 1024"
              width="14"
              height="14"
              style="vertical-align: -2px"
            >
              <use xlink:href="#icon-zuozhe" />
            </svg>
            <span>&nbsp;{{ article.createBy }}</span>
            <span>·</span>

            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-rili" />
            </svg>
            <span>&nbsp;{{ article.createTime }}</span>
            <span>·</span>

            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-redu" />
            </svg>
            <span>&nbsp;{{ article.viewCount }}</span>
            <span>·</span>

            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-yidianzan" />
            </svg>
            <span>&nbsp;{{ article.likeCount }}</span>
            <span>·</span>

            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-pinglun" />
            </svg>
            <span>&nbsp;{{ article.commentCount }}</span>
          </div>
        </div>
      </div>
      <!-- 文章 -->
      <div style="background: var(--background)">
        <div class="article-container my-animation-slide-bottom">
          <div
            v-if="!$common.isEmpty(article.videoUrl)"
            style="margin-bottom: 20px"
          ></div>

          <!-- 文章内容 -->
          <div v-html="articleContentHtml" class="entry-content"></div>
          <!-- 最后更新时间 -->
          <div class="article-update-time">
            <span>文章最后更新于: {{ article.updateTime }}</span>
          </div>
          <!-- 分类 -->
          <div class="article-sort">
            <span
              @click="
                $router.push({
                  path: '/articlePage',
                  query: { sortId: article.sortId, labelId: article.labelId },
                })
              "
            >
              {{ sortName }}" ▶ "{{ labelName }}
            </span>
          </div>
          <!-- 作者信息 -->
          <blockquote>
            <div>作者：{{ article.createBy }}</div>
            <div>版权声明：转载请注明文章出处</div>
          </blockquote>
          <!-- 订阅 -->
          <div class="myCenter" id="article-like" @click="subscribeLabel()">
            <i
              class="el-icon-thumb article-like-icon"
              :class="{ 'article-like': subscribe }"
            ></i>
          </div>

          <!-- 评论 -->
          <div>
            <comment
              :type="'article'"
              :source="article.id"
              :count="article.commentCount"
              :comment-status="article.commentStatus"
            />
          </div>
        </div>

        <div id="toc" class="toc"></div>
      </div>

      <div style="background: var(--background)">
        <my-footer />
      </div>

      <div id="toc-button" @click="clickTocButton()">
        <i class="fa fa-align-justify" aria-hidden="true"></i>
      </div>
    </div>
  </div>
</template>

<script>
const myFooter = () => import("../common/footer.vue");
const comment = () => import("../comment/comment");
import MarkdownIt from "markdown-it";

export default {
  components: {
    myFooter,
    comment,
  },

  data() {
    return {
      id: this.$route.query.id,
      article: {},
      articleContentHtml: "",
      showSubscribe: false,
      scrollTop: 0,

      subscribe: false,
    };
  },
  created() {
    if (!this.$common.isEmpty(this.id)) {
      this.getArticle(this.id);

      if (!this.showSubscribe) {
        this.$notify({
          title: "文章订阅",
          type: "success",
          message: "点击文章下方小手 - 订阅/取消订阅专栏（标签）",
          duration: 0,
          onClose: () => (this.showSubscribe = false),
        });
        this.showSubscribe = true;
      }
    }
  },
  computed: {
    sortName() {
      return this.$store.state.sortInfo.filter((f) => {
        return f.sortId === this.article.sortId;
      })[0].sortName;
    },
    labelName() {
      return this.$store.state.labelInfo.filter((f) => {
        return f.labelId === this.article.labelId;
      })[0].labelName;
    },
  },
  mounted() {
    window.addEventListener("scroll", this.onScrollPage);
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScrollPage);
  },
  watch: {
    scrollTop(scrollTop, oldScrollTop) {
      let isShow = scrollTop - window.innerHeight > 30;
      if (isShow) {
        $("#toc-button").css("bottom", "15vh");
      } else {
        $("#toc-button").css("bottom", "8vh");
      }
    },
  },
  methods: {
    getArticle(id) {
      this.$createHttp
        .getArticleById(id)
        .then((res) => {
          if (res.code === 200) {
            this.article = res.data;
            const md = new MarkdownIt({ breaks: true }).use(
              require("markdown-it-multimd-table")
            );
            this.articleContentHtml = md.render(this.article.articleContent);
            this.$nextTick(() => {
              this.highlight();
              this.addId();
              this.getTocbot();
            });
          }
        })
        .catch((error) => {
          this.$message({
            message: error,
            type: "error",
          });
        });
    },
    //文章内容标题
    addId() {
      let headings = $(".entry-content").find("h1, h2, h3, h4, h5, h6");
      headings.attr("id", (i, id) => id || "toc-" + i);
    },
    //目录
    getTocbot() {
      let script = document.createElement("script");
      script.type = "text/javascript";
      script.src = this.$constant.tocbot;
      document.getElementsByTagName("head")[0].appendChild(script);

      // 引入成功
      script.onload = function () {
        tocbot.init({
          tocSelector: "#toc",
          contentSelector: ".entry-content",
          headingSelector: "h1, h2, h3, h4, h5",
          scrollSmooth: true,
          fixedSidebarOffset: "auto",
          scrollSmoothOffset: -100,
          hasInnerContainers: false,
        });
      };
    },
    //markdown样式转换
    highlight() {
      let attributes = {
        autocomplete: "off",
        autocorrect: "off",
        autocapitalize: "off",
        spellcheck: "false",
        contenteditable: "false",
      };

      $("pre").each(function (i, item) {
        let preCode = $(item).children("code");
        let classNameStr = preCode[0].className;
        let classNameArr = classNameStr.split(" ");

        let lang = "";
        classNameArr.some(function (className) {
          if (className.indexOf("language-") > -1) {
            lang = className.substring(
              className.indexOf("-") + 1,
              className.length
            );
            return true;
          }
        });

        // 检测语言是否存在，不存在则自动检测
        let language = hljs.getLanguage(lang.toLowerCase());
        if (language === undefined) {
          // 启用自动检测
          let autoLanguage = hljs.highlightAuto(preCode.text());
          preCode.removeClass("language-" + lang);
          lang = autoLanguage.language;
          if (lang === undefined) {
            lang = "java";
          }
          preCode.addClass("language-" + lang);
        } else {
          lang = language.name;
        }

        $(item).addClass("highlight-wrap");
        $(item).attr(attributes);
        preCode
          .attr("data-rel", lang.toUpperCase())
          .addClass(lang.toLowerCase());
        // 启用代码高亮
        hljs.highlightBlock(preCode[0]);
        // 启用代码行号
        hljs.lineNumbersBlock(preCode[0]);
      });

      $("pre code").each(function (i, block) {
        $(block).attr({
          id: "hljs-" + i,
        });

        $(block).after(
          '<a class="copy-code" href="javascript:" data-clipboard-target="#hljs-' +
            i +
            '"><i class="fa fa-clipboard" aria-hidden="true"></i></a>'
        );
        new ClipboardJS(".copy-code");
      });

      if ($(".entry-content").children("table").length > 0) {
        $(".entry-content")
          .children("table")
          .wrap("<div class='table-wrapper'></div>");
      }
    },
    clickTocButton() {
      let display = $(".toc");
      if ("none" === display.css("display")) {
        display.css("display", "unset");
      } else {
        display.css("display", "none");
      }
    },
    onScrollPage() {
      this.scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (this.scrollTop < window.innerHeight / 4) {
        $(".toc").css("top", window.innerHeight / 4);
      } else {
        $(".toc").css("top", "90px");
      }
    },

    // todo 订阅函数待实现
    subscribeLabel() {
      if (this.$common.isEmpty(localStorage.getItem("token"))) {
        this.$message({
          message: "请先登录！",
          type: "error",
        });
        return;
      }

      let labelName = this.labels.filter((f) => {
        return f.labelId === this.article.labelId;
      })[0].labelName;

      this.$confirm(
        "确认" +
          (this.subscribe ? "取消订阅" : "订阅") +
          "专栏【" +
          labelName +
          "】？" +
          (this.subscribe
            ? ""
            : "订阅专栏后，该专栏发布新文章将通过邮件通知订阅用户。"),
        this.subscribe ? "取消订阅" : "文章订阅",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          center: true,
        }
      )
        .then(() => {
          //todo 订阅逻辑
        })
        .catch(() => {
          this.$message({
            type: "success",
            message: "已取消!",
          });
        });
    },
  },
};
</script>

<style scoped>
.article-head {
  height: 40vh;
  position: relative;
}

.article-image::before {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: var(--miniMask);
  content: "";
}

.article-info-container {
  position: absolute;
  bottom: 15px;
  left: 20%;
  color: var(--white);
}

.article-title {
  font-size: 28px;
  margin-bottom: 15px;
}

.article-info {
  font-size: 14px;
  user-select: none;
}

.article-info i {
  margin-right: 6px;
}

.article-info span:not(:last-child) {
  margin-right: 5px;
}

.article-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
}

.article-update-time {
  color: var(--greyFont);
  font-size: 12px;
  margin: 20px 0;
  user-select: none;
}

blockquote {
  line-height: 2;
  border-left: 0.2rem solid var(--blue);
  padding: 10px 1rem;
  background-color: var(--azure);
  border-radius: 4px;
  margin: 0 0 40px 0;
  user-select: none;
  color: var(--black);
}

.article-sort {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.article-sort span {
  padding: 3px 10px;
  background-color: var(--themeBackground);
  border-radius: 5px;
  font-size: 14px;
  color: var(--white);
  transition: all 0.3s;
  margin-right: 25px;
  cursor: pointer;
  user-select: none;
}

.article-sort span:hover {
  background-color: var(--red);
}

.article-like {
  color: var(--red) !important;
}

.article-like-icon {
  font-size: 60px;
  cursor: pointer;
  color: var(--greyFont);
  transition: all 0.5s;
  border-radius: 50%;
  margin-bottom: 20px;
}

.article-like-icon:hover {
  transform: rotate(360deg);
}

.process-wrap hr {
  position: relative;
  margin: 10px auto 60px;
  border: 2px dashed var(--lightGreen);
  overflow: visible;
}

.process-wrap hr:before {
  position: absolute;
  top: -14px;
  left: 5%;
  color: var(--lightGreen);
  content: "❄";
  font-size: 30px;
  line-height: 1;
  transition: all 1s ease-in-out;
}

.process-wrap hr:hover:before {
  left: calc(95% - 20px);
}

.process-wrap >>> .el-collapse-item__header {
  border-bottom: unset;
  font-size: 20px;
  background-color: var(--background);
  color: var(--lightGreen);
}

.process-wrap >>> .el-collapse-item__wrap {
  background-color: var(--background);
}

.process-wrap .el-collapse {
  border-top: unset;
  border-bottom: unset;
}

.process-wrap >>> .el-collapse-item__wrap {
  border-bottom: unset;
}

#toc-button {
  position: fixed;
  right: 3vh;
  bottom: 8vh;
  animation: slide-bottom 0.5s ease-in-out both;
  z-index: 100;
  cursor: pointer;
  font-size: 23px;
  width: 30px;
}

#toc-button:hover {
  color: var(--themeBackground);
}

@media screen and (max-width: 700px) {
  .article-info-container {
    left: 20px;
    max-width: 320px;
  }
}

@media screen and (max-width: 400px) {
  #toc-button {
    right: 0.5vh;
  }
}
</style>
